import {Component,Input,Output,EventEmitter,OnInit,OnChanges} from "@angular/core";
import {NzNotificationService,NzModalSubject,NzModalService,UploadFile} from "ng-zorro-antd";
import {HttpServcie} from "../../../service/http.service";
import {Config} from "../../../service/config";
import {SpotCheckItems} from "../../maintenancePlan/bean/spotCheckItem";
import {FormBuilder, FormControl, FormGroup, Validators} from "@angular/forms";

@Component({
  selector: "spot-check-item",
  templateUrl: "spot-check-item.html",
  styleUrls: ["spot-check-item.scss"]
})
export class SpotCheckItem implements OnInit, OnChanges {
  public isSpinning: boolean = false;
  @Output("outPut")
  public outPut = new EventEmitter();
  @Input()
  public inValue: any = [];
  public config: any = Config;

  spotCheckItem:SpotCheckItems = new SpotCheckItems();

  // 定义计划信息数据
  public planInfo:any=[];

  // 定义已经保存到库里的检查项
  public checkItems:any=[];

  // 定义曳引与强制驱动电梯检查项目
  public yeItemList:any=[];
  public productallChecked = false;   // 复选框
  public productindeterminate = false;


  // 定义液压驱动电梯
  public hydraulicList:any=[];
  public usedallChecked = false;   //复选框
  public usedindeterminate = false;


  // 定义杂物电梯检查项目
  public variaList:any=[];
  public elevatorallChecked = false;  // 复选框
  public elevatorindeterminate = false;

  // 定义自动电梯检查项目
  public automaticList:any=[];
  public selfallChecked = false;    // 复选框
  public selfindeterminate = false;


  // 定义自定义电梯检查项目
  public customList:any=[];
  public customallChecked = false;     // 复选框
  public customindeterminate = false;


  // 定义登录者信息
  public user: any = {};
  // 定义模态框表头
  public currentModal: any;
  // 定义自定义检查清单数据
  public inCheckItemData: any = {};


  public validateForm: FormGroup;
  public controlArray:any = [];

  // 定义自定义输入的内容数据
  public customs:any=[];


  constructor(
    private fb: FormBuilder,
    private httpServcie: HttpServcie,
    private _notification: NzNotificationService,
    private nsub: NzModalSubject,
    private modalService: NzModalService
  ) { }

  ngOnInit() {
    this.user = JSON.parse(window.localStorage.getItem("user"));
    // 主表的计划信息
    this.planInfo =  this.inValue.clickItemDate;
    console.log(this.planInfo);

    this.validateForm = this.fb.group({});
    this.addField();


  }

  ngOnChanges() {
    // 获取已经保存的检查项
    this.findCheckItem(this.inValue.clickItemDate[0]);



    // 定义曳引与强制电梯检查项目
    let itemType: any = ['4', '5', '6', '7'];
    this.httpServcie.querySpotCheckItem({"itemType": itemType,"itemName":"维护保养"}).subscribe(data => {
      if (data.status == 200) {
        console.log(data.data);
        for (let i = 0; i < data.data.length; i++) {
          if (data.data[i].itemType == "4") {
            if(this.checkItems.indexOf(data.data[i].id) !=-1){
              data.data[i].checked = true;
            }
            this.yeItemList.push(data.data[i]);
          }
          if (data.data[i].itemType == "5") {
            if(this.checkItems.indexOf(data.data[i].id) !=-1){
              data.data[i].checked = true;
            }
            this.hydraulicList.push(data.data[i]);
          }

          if (data.data[i].itemType == "6") {
            if(this.checkItems.indexOf(data.data[i].id) !=-1){
              data.data[i].checked = true;
            }
            this.variaList.push(data.data[i]);
          }

          if (data.data[i].itemType == "7") {
            if(this.checkItems.indexOf(data.data[i].id) !=-1){
              data.data[i].checked = true;
            }
            this.automaticList.push(data.data[i]);
          }
        }
      }
    });
  }

  // 查询检查项
  findCheckItem(planId: string) {

    this.httpServcie.findSpotCheckItem({"planId": planId}).subscribe(data => {
      if (data.status == 200) {
        for (let i = 0; i < data.data.length; i++) {
          // 基础维护项
          if (data.data[i].isCustom == "N") {
            this.checkItems.push(data.data[i].itemId);
          }
          if (data.data[i].isCustom == "Y") {
              data.data[i].checked = true;
            // 自定义维护项
            this.customList.push(data.data[i]);
          }
        }
      }
    });
  }


  // 保存检查项
  submitForm($event) {

    // 定义变量 用于保存具体检查哪几项
    const updateList: any = [];
    // 曳引
    this.yeItemList.forEach(element => {
      if (element.checked) {
        updateList.push(element.id);
      }
    });
    // 液压驱动
    this.hydraulicList.forEach(element => {
      if (element.checked) {
        updateList.push(element.id);
      }
    });
    // 杂物电梯
    this.variaList.forEach(element => {
      if (element.checked) {
        updateList.push(element.id);
      }
    });
    //自动电梯
    this.automaticList.forEach(element => {
      if (element.checked) {
        updateList.push(element.id);
      }
    });

    if(updateList.length==0 || updateList==null){
      this._notification.create("warning", "警告提示", "请先选择维保项！");
      return;
    }

    this.isSpinning=true;

    // 保存检查项  先支持多选，用list，后面改掉了，list就没有变
    let ob = this.httpServcie.addSpotCheckItem({ "updateList": updateList.join(","),"planInfo":this.planInfo.join(","),"custom":this.customs.join(",")});
    ob.subscribe(data => {
      this.isSpinning = false;
      if (data.status == 200) {
        this._notification.create("success", "成功提示", "添加成功");
        /*this.ngOnChanges();*/
        this.outPut.emit($event);
      } else {
        this._notification.create("error", "失败提示", data.message);
        return;
      }
    });
  }

  //定义曳引与强制电梯检查项目 table加载数据时
  productdisplayDataChange($event) {
    this.yeItemList = $event;
    this.productrefreshStatus();
  }
  //重置选择框
  productrefreshStatus() {
    const allChecked = this.yeItemList.every(
      value => value.disabled || value.checked
    );
    const allUnChecked = this.yeItemList.every(
      value => value.disabled || !value.checked
    );
    this.productallChecked = allChecked;
    this.productindeterminate = !allChecked && !allUnChecked;
  }
  //全选
  productcheckAll(value) {
    if (value) {
      this.yeItemList.forEach(data => {
        if (!data.disabled) {
          data.checked = true;
        }
      });
    } else {
      this.yeItemList.forEach(data => (data.checked = false));
    }
  }
  // ---------------------------end--------------------------------

  //液压驱动  table加载数据时
  useddisplayDataChange($event) {
    this.hydraulicList = $event;
    this.usedrefreshStatus();
  }
  //重置选择框
  usedrefreshStatus() {
    const allChecked = this.hydraulicList.every(
      value => value.disabled || value.checked
    );
    const allUnChecked = this.hydraulicList.every(
      value => value.disabled || !value.checked
    );
    this.usedallChecked = allChecked;
    this.usedindeterminate = !allChecked && !allUnChecked;
  }
  //全选
  usedcheckAll(value) {
    if (value) {
      this.hydraulicList.forEach(data => {
        if (!data.disabled) {
          data.checked = true;
        }
      });
    } else {
      this.hydraulicList.forEach(data => (data.checked = false));
    }
  }
  // ---------------------------end--------------------------------

  // 杂物电梯 table加载数据时
  elevatordisplayDataChange($event) {
    this.variaList = $event;
    this.elevatorrefreshStatus();
  }
  //重置选择框
  elevatorrefreshStatus() {
    const allChecked = this.variaList.every(
      value => value.disabled || value.checked
    );
    const allUnChecked = this.variaList.every(
      value => value.disabled || !value.checked
    );
    this.elevatorallChecked = allChecked;
    this.elevatorindeterminate = !allChecked && !allUnChecked;
  }
  //全选
  elevatorcheckAll(value) {
    if (value) {
      this.variaList.forEach(data => {
        if (!data.disabled) {
          data.checked = true;
        }
      });
    } else {
      this.variaList.forEach(data => (data.checked = false));
    }
  }
  // ---------------------------end--------------------------------

  //自动电梯 table加载数据时
  selfdisplayDataChange($event) {
    this.automaticList = $event;
    this.selfrefreshStatus();
  }
  //重置选择框
  selfrefreshStatus() {
    const allChecked = this.automaticList.every(
      value => value.disabled || value.checked
    );
    const allUnChecked = this.automaticList.every(
      value => value.disabled || !value.checked
    );
    this.selfallChecked = allChecked;
    this.selfindeterminate = !allChecked && !allUnChecked;
  }
  //全选
  selfcheckAll(value) {
    if (value) {
      this.automaticList.forEach(data => {
        if (!data.disabled) {
          data.checked = true;
        }
      });
    } else {
      this.automaticList.forEach(data => (data.checked = false));
    }
  }
  // ---------------------------end--------------------------------

  //自定义 table加载数据时
  customdisplayDataChange($event) {
    this.customList = $event;
    this.customrefreshStatus();
  }

  //重置选择框
  customrefreshStatus() {
    const allChecked = this.customList.every(
      value => value.disabled || value.checked
    );
    const allUnChecked = this.customList.every(
      value => value.disabled || !value.checked
    );
    this.customallChecked = allChecked;
    this.customindeterminate = !allChecked && !allUnChecked;
  }

  //全选
  customcheckAll(value) {
    if (value) {
      this.customList.forEach(data => {
        if (!data.disabled) {
          data.checked = true;
        }
      });
    } else {
      this.customList.forEach(data => (data.checked = false));
    }
  }

  cancel($event) {
    this.outPut.emit($event);
  }

  // 自定义里的删除

  deleteItem(){
    let customData:any=[];
    let flag:boolean=false;
    let ids:any=[];
    this.customList.forEach(element => {
      if (element.checked) {
        console.log(element);
        ids.push(element.id);
      }
    });

    if(ids.length==0){
      this._notification.create("warning", "警告提示", "请先选择您要删除的数据！");
      return;
    }

    let ob = this.httpServcie.deleteCustomCheckItem({ "ids": ids.join(",")});
    ob.subscribe(data => {
      if (data.status == 200) {
        this._notification.create("success", "成功提示", "删除成功");
        flag=true;
      } else {
        this._notification.create("error", "失败提示", data.message);
        return;
      }
      if(flag){
        this.httpServcie.findSpotCheckItem({"planId": this.inValue.clickItemDate[0]}).subscribe(data => {
          if (data.status == 200) {
            for (let i = 0; i < data.data.length; i++) {
              if (data.data[i].isCustom == "Y") {
                data.data[i].checked = true;
                customData.push(data.data[i]);
                // 自定义维护项
              }
            }
            this.customList = customData;
          }
        });
      }
    });
  }


  addField(e?: MouseEvent) {
    if (e) {
      e.preventDefault();
    }
    const id = (this.controlArray.length > 0) ? this.controlArray[this.controlArray.length - 1].id + 1 : 0;

    const control = {
      id,
      controlInstance: `passenger${id}`
    };
    const index = this.controlArray.push(control);
    console.log(this.controlArray[this.controlArray.length - 1]);
    this.validateForm.addControl(this.controlArray[index - 1].controlInstance, new FormControl(null, Validators.required));
  }

  removeField(i, e: MouseEvent) {
    e.preventDefault();
    if (this.controlArray.length > 1) {
      const index = this.controlArray.indexOf(i);
      this.controlArray.splice(index, 1);
      console.log(this.controlArray);
      this.validateForm.removeControl(i.controlInstance);
    }
  }

  getFormControl(name) {
    return this.validateForm.controls[name];
  }

  _submitForm() {
    let items:any = [];
    for (const i in this.validateForm.controls) {
      let froms = this.validateForm.controls[i].value;
      if(froms !=null && froms!=undefined && froms !=""){
        items.push(this.validateForm.controls[i].value);
      }
      console.log(this.validateForm.controls[i].value);
      this.validateForm.controls[i].markAsDirty();
    }
    if(items.length ==0 || items==null){
      this._notification.create("warning", "警告提示", "您还未添加自定义检查项！");
      return false;
    }else{
      this._notification.create("success", "成功提示", "自定义项提交成功，请点击确定！");
    }
    this.customs = items;


  }

}
